package me.yuzhou.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import me.yuzhou.weixin.util.CheckUtil;
import me.yuzhou.weixin.util.MessageUtil;

public class WeixinServlet extends HttpServlet {
	
	private static final Logger logger = LoggerFactory.getLogger(WeixinServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		//获取微信中心传过来的4个参数
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce  = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		
		logger.info("signature: {}", signature);
		logger.info("timestamp: {}", timestamp);
		logger.info("nonce: {}", nonce);
		logger.info("echostr: {}", echostr);
		
		//通过检验signature对请求进行校验
		PrintWriter out = res.getWriter();
		if(CheckUtil.checkSignature(signature, timestamp, nonce)){
			out.print(echostr);
		}
	}

	private static final long serialVersionUID = 8726570958750276151L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		try {
			Map<String, String> map = MessageUtil.xmlToMap(request);
			
			logger.info("Request Map: {}", map);
			
			String fromUserName = map.get("FromUserName");
			String toUserName = map.get("ToUserName");
			String createTime = map.get("CreateTime");
			String msgType = map.get("MsgType");
			String content = map.get("Content");
			String msgId = map.get("MsgId");
			
			logger.info("Receive {} msg {} form {} at {} , Content: \n{}", 
					msgType, msgId, fromUserName, 
					new Date(Long.parseLong(createTime)*1000), content);
			
			String message = null;
			if(MessageUtil.MESSAGE_TEXT.equals(msgType)) {    
				if("1".equals(content)){
					message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.firstMenuText());
				} else if("2".equals(content)){
					message = MessageUtil.initNewsMessage(toUserName, fromUserName);
				} else if("3".equals(content)){
					message = MessageUtil.initImageMessage(toUserName, fromUserName);
				} else if("4".equals(content)){
					message = MessageUtil.initMusicMessage(toUserName, fromUserName);
				} else if("?".equals(content) || "？".equals(content)){
					message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
				}else {
					message = MessageUtil.initText(toUserName, fromUserName, "您发送的消息是："+ content);
				}
				
			} else if(MessageUtil.MESSAGE_EVENT.equals(msgType)) {
				String eventType = map.get("Event");
				
				logger.info("Event Type: {}", eventType);
				if(MessageUtil.EVENT_SUBSCRIBE.equals(eventType)) {
					message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
				} else if(MessageUtil.EVENT_CLICK.equals(eventType)) {
					
					message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
					
				} else if(MessageUtil.EVENT_VIEW.equals(eventType)) {
					String url = map.get("EventKey");
					message = MessageUtil.initText(toUserName, fromUserName, url);
				} else if(MessageUtil.EVENT_SCANCODE.equals(eventType)) {
					String key = map.get("EventKey");
					message = MessageUtil.initText(toUserName, fromUserName, key);
				}
			} else if(MessageUtil.MESSAGE_LOCATION.equals(msgType)) {
				String label = map.get("Label");
				message = MessageUtil.initText(toUserName, fromUserName, label);
			}
			
			logger.info("Message:\n {}", message);
			out.print(message);		
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}finally {
			out.close();
		}
	}
	
	

}
